#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <unordered_map>
#include "Tcp_Server.hpp"
#include "HttpCrtl.hpp"

using namespace std;
using namespace Tcp_module;
using http_handler_t = function<void(HttpRequest &, HttpResponse &)>;

class HttpServer
{
private:
    //功能处理
    unordered_map<string, http_handler_t> _handlers;
    unique_ptr<Tcp_Server> _server;

public:
    HttpServer(int port):_server(make_unique<Tcp_Server>(port)){}
    ~HttpServer(){}
    void Resgiter(const string &url, const http_handler_t &handler)
    {
        _handlers[url] = handler;
    }
    bool SafeCheck(const std::string &service)
    {
        auto iter = _handlers.find(service);
        return iter != _handlers.end();
    }
    void Start()
    {
    _server->init([this](SockPtr sock, InetAddr Client){
        return this->HandlerHttp(sock, Client);
    });
    _server->loop();
    }
    
    bool HandlerHttp(SockPtr sockfd, InetAddr Client)
    {
        LOG(LogLevel::DEBUG) << "HttpServer: get a new client: " << sockfd->Fd() << " addr info: " << Client.Addr();
        string http_request;
        sockfd->Recv(&http_request);
        LOG(LogLevel::DEBUG) << "HttpServer: recv http request: " << http_request;
        HttpRequest req;
        req.Deserialize(http_request);
        HttpResponse res;
        // 请求应该被分成两类: 1. 请求一般的静态资源 2. 提交参数，携带参数，需要我们进行交互设置
        if(req.IsHasArgs())
        {
            string server=req.Path();
            if(SafeCheck(server))
            {
                _handlers[server](req,res);
            }
            else
            {
                res.Build(req);
            }
        }
        else
        {
            res.Build(req);
        }
        string str;
        res.Serialize(&str);
        LOG(LogLevel::DEBUG) << "HttpServer: send http response: " << str;
        sockfd->Send(str);
        return true;
    }
};